#include "timer.h"
#include "stm32f10x.h"
#include "pin_map.h"
#include "stm32f10x_tim.h"

// 回调函数数组（每个定时器一个）
static void (*timer_callbacks[4])(void) = {NULL};

// 定义配置结构体类型
typedef struct {
    TIM_TypeDef* tim;
    uint32_t     rcc_periph;        // RCC 外设定义
    uint8_t      irq_channel;       // 中断通道
} timer_config_t;

// 定时器配置表（私有）
static const timer_config_t timer_config[4] = {
    { TIM2, RCC_APB1Periph_TIM2, TIM2_IRQn },
    { TIM3, RCC_APB1Periph_TIM3, TIM3_IRQn },
    { TIM4, RCC_APB1Periph_TIM4, TIM4_IRQn },
    { TIM5, RCC_APB1Periph_TIM5, TIM5_IRQn }
};

// ---------------- API 实现 ----------------
/*
  prescaler的范围为1 ~ 65536
*/
int timerBegin(uint8_t timer_num, uint16_t prescaler, uint8_t count_up) {
    if (timer_num >= 4) return -1;

    const timer_config_t *cfg = &timer_config[timer_num];
    TIM_TypeDef* tim = cfg->tim;

    // 使能时钟（使用标准库函数）
    RCC_APB1PeriphClockCmd(cfg->rcc_periph, ENABLE);

    // 基本定时器配置
    TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
    TIM_TimeBaseStructure.TIM_Prescaler = prescaler - 1;           // 硬件自动 +1
    TIM_TimeBaseStructure.TIM_Period = 0xFFFF;                     // 临时
    TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
    TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1;
    TIM_TimeBaseInit(tim, &TIM_TimeBaseStructure);

    // 禁用定时器和中断
    TIM_Cmd(tim, DISABLE);
    TIM_ITConfig(tim, TIM_IT_Update, DISABLE);

    return 0;
}

/**
 * @brief  读取指定定时器的当前计数值
 */
uint16_t timerRead(uint8_t timer_num)
{
    if (timer_num >= 4) {
        return 0;  // 无效定时器编号
    }

    const timer_config_t *cfg = &timer_config[timer_num];
    return (uint16_t)(cfg->tim->CNT);  // CNT 是 32 位寄存器，但只用低 16 位
}

/**
 * @brief  设置指定定时器的当前计数值
 */
void timerWrite(uint8_t timer_num, uint16_t value)
{
    if (timer_num >= 4) {
        return;
    }

    const timer_config_t *cfg = &timer_config[timer_num];
    cfg->tim->CNT = value;  // 写入 CNT 寄存器
}

void timerAttachInterrupt(uint8_t timer_num, void (*callback)(void)) {
    if (timer_num < 4) {
        timer_callbacks[timer_num] = callback;
    }
}

/*
  ARR为1 ~ 65,535
*/
void timerAlarmWrite(uint8_t timer_num, uint32_t alarm_value, uint8_t auto_reload) {
    if (timer_num >= 4) return;


    TIM_TypeDef* tim = timer_config[timer_num].tim;
	
	// 所有 TIM2~TIM5 都是 16 位，ARR 最大 65535
    if (alarm_value == 0 || alarm_value > 65535) {
        alarm_value = 65535;  // 或报错
    }
	
    TIM_SetAutoreload(tim, alarm_value - 1);  // ARR = N-1
    TIM_SetCounter(tim, 0);

    if (auto_reload) {
        tim->CR1 &= ~TIM_CR1_OPM;
    } else {
        tim->CR1 |= TIM_CR1_OPM;
    }
}

void timerAlarmEnable(uint8_t timer_num) {
    if (timer_num >= 4) return;
	
    const timer_config_t *cfg = &timer_config[timer_num];
    TIM_TypeDef* tim = cfg->tim;

    TIM_ITConfig(tim, TIM_IT_Update, ENABLE);
    TIM_Cmd(tim, ENABLE);

    // NVIC 配置
    NVIC_InitTypeDef NVIC_InitStructure;
    NVIC_InitStructure.NVIC_IRQChannel = cfg->irq_channel;
    NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 10;
    NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
    NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
    NVIC_Init(&NVIC_InitStructure);
}

void timerStop(uint8_t timer_num) {
    if (timer_num >= 4) return;
    TIM_TypeDef* tim = timer_config[timer_num].tim;
    TIM_Cmd(tim, DISABLE);
    TIM_ITConfig(tim, TIM_IT_Update, DISABLE);
}

void TIM2_IRQHandler(void) {
    if (TIM2->SR & TIM_SR_UIF) {
        TIM2->SR &= ~TIM_SR_UIF;
        if (timer_callbacks[0]) timer_callbacks[0]();
    }
}

void TIM3_IRQHandler(void) {
    if (TIM3->SR & TIM_SR_UIF) {
        TIM3->SR &= ~TIM_SR_UIF;
        if (timer_callbacks[1]) timer_callbacks[1]();
    }
}

void TIM4_IRQHandler(void) {
    if (TIM4->SR & TIM_SR_UIF) {
        TIM4->SR &= ~TIM_SR_UIF;
        if (timer_callbacks[2]) timer_callbacks[2]();
    }
}

void TIM5_IRQHandler(void) {
    if (TIM5->SR & TIM_SR_UIF) {
        TIM5->SR &= ~TIM_SR_UIF;
        if (timer_callbacks[3]) timer_callbacks[3]();
    }
}
